package structral;

import java.util.ArrayList;

/**
 * 组合模式（composition） 将对象组合成树形结构以表示部分整体的层次结构 组合模式使得用户对单个对象和组合对象的使用具有一致性
 * 
 * @author 关关
 *
 */
public abstract class Component {
	public static void main(String[] args) {
		Component r = new Composite("root");
		Component la = new Composite("Leaf A");
		
		r.Add(la);
		r.Add(new Leaf("Leaf B"));

		Component ca = new Composite("comp");
		ca.Add(new Leaf("Leaf XA"));
		ca.Add(new Leaf("Leaf XB"));
		r.Add(ca);
		la.Add(ca);

		Component l1 = new Leaf("li");
		l1.Add(new Leaf("Leaf XYA"));
		l1.Add(new Leaf("Leqaf XYB"));
		ca.Add(l1);

		r.Add(new Leaf("Leaf C"));

		Leaf leaf = new Leaf("Leaf D");
		r.Add(leaf);
		r.Remove(leaf);

		r.show(0);

	}

	public String Name;

	// 显式方法
	public void show(int i) {
		StringBuilder sBuilder = new StringBuilder();
		for (int j = 0; j < i; j++) {
			sBuilder.append("-");
		}
		System.out.println(String.format("%s%s", sBuilder, Name));

	}

	public Component(String name) {
		this.Name = name;
	}

	public abstract void Add(Component c);// 添加子节点

	public abstract void Remove(Component c);// 删除子节点
}

// 枝节点
class Composite extends Component {
	public Composite(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	ArrayList<Component> components = new ArrayList<Component>();// 需要聚合关联父类节点

	public void show(int i) {//重写show方法
		super.show(i);//输出自己
		for (int j = 0; j < components.size(); j++) {//输出下一节子节点
			components.get(j).show(i + 1);
		}
	}

	@Override
	public void Add(Component c) {
		// TODO Auto-generated method stub
		components.add(c);
	}

	@Override
	public void Remove(Component c) {
		// TODO Auto-generated method stub
		components.remove(c);
	}
}

// 叶节点
class Leaf extends Component {

	public Leaf(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void Add(Component c) {
		// TODO Auto-generated method stub

	}

	@Override
	public void Remove(Component c) {
		// TODO Auto-generated method stub

	}

}
